﻿using log4net;
using Mathmall.Administration.Data;
using Mathmall.Administration.Models;
using Mathmall.Administration.Vo;
using Microsoft.EntityFrameworkCore;

namespace Mathmall.Administration.Mapper
{
    public class BrandMapper : BaseMapper
    {
        private static readonly ILog _logger = LogManager.GetLogger(typeof(BrandMapper));

        public BrandMapper(AdministrationContext context) : base(context)
        {
        }

        /// <summary>
        /// 保存品牌信息
        /// </summary>
        /// <param name="brand"></param>
        /// <returns></returns>
        public async Task<int> AddBrand(Brand brand)
        {
            _context.Add(brand);
            return await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 根据BrandId查询品牌信息
        /// </summary>
        /// <param name="brandId"></param>
        /// <returns></returns>
        public async Task<Brand?> QuerySingleByBrandId(int brandId)
        {
            var brand = await _context.Brands
                .AsNoTracking()
                .SingleOrDefaultAsync(brand => brandId.Equals(brand.BrandID));
            return brand;
        }

        /// <summary>
        /// 查询全部
        /// </summary>
        /// <returns></returns>
        public IQueryable<Brand> QueryListByCondition(string condition)
        {
            var brands = _context.Brands.Where(brand => brand.Name!.Contains(condition));
            return brands;
        }

        /// <summary>
        /// 更新品牌信息
        /// </summary>
        /// <param name="brand"></param>
        public async Task<int> Update(Brand brand)
        {
            return await _context.Brands.Where(b => b.BrandID.Equals(brand.BrandID))
                .ExecuteUpdateAsync(setter => setter
                    .SetProperty(b => b.Name, brand.Name)
                    .SetProperty(b => b.Logo, brand.Logo)
                    .SetProperty(b => b.Description, brand.Description)
                    .SetProperty(b => b.ShowStatus, brand.ShowStatus)
                    .SetProperty(b => b.FirstLetter, brand.FirstLetter)
                    .SetProperty(b => b.Sort, brand.Sort));
        }

        /// <summary>
        /// 删除品牌
        /// </summary>
        /// <param name="brandIds"></param>
        /// <returns></returns>
        public async Task<int> Delete(List<int> brandIds)
        {
            return await _context.Brands.Where(b => brandIds.Contains(b.BrandID)).ExecuteDeleteAsync();
        }
    }
}